import { createSlice } from "@reduxjs/toolkit";

export const authSlice = createSlice({
    name: 'auth',
    // initialState: {
    //     isLogged: false,
    //     token: null,
    //     user: null
    // },
    // 除了指定obj为值，也可以指定一个函数作为属性值，这样就可以添加逻辑了
    initialState: () => {
        const token = localStorage.getItem('token')
        if (!token) {
            return {
                isLogged: false,
                token: null,    // token是存在有效期的，因此需要在一定的时间后，清除登录状态，重新登录更新token，strap默认1个月的有效期
                user: null,
                expirationTime: 0   // 登录状态过期时间
            }
        }
        return {
            isLogged: true,
            token,
            user: JSON.parse(localStorage.getItem('user')),
            expirationTime: +localStorage.getItem('expirationTime')
        }
    },
    reducers: {
        login(state, action) {
            state.isLogged = true
            state.token = action.payload.token
            state.user = action.payload.user
            localStorage.setItem('token', state.token)
            localStorage.setItem('user', JSON.stringify(state.user))
            const currentTime = Date.now()
            // const timeout = 1000 * 60 * 60 * 24 * 7 // 一周
            const timeout = 10000 // 10秒

            state.expirationTime = currentTime + timeout    // 设置失效时间
            localStorage.setItem('expirationTime', state.expirationTime + '')
        },
        loginout(state, action) {
            state.isLogged = false
            state.token = null
            state.user = null
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            localStorage.removeItem('expirationTime')
        }
    }
})

export const {login, loginout} = authSlice.actions